package com.td.filemanager.business.device;

import com.td.filemanager.ResourceTable;
import com.td.filemanager.provider.ComponentViewHolder;
import com.td.filemanager.provider.ListComponentProvider;
import com.td.library.data.DeviceData;
import com.td.library.utils.LogUtil;
import ohos.agp.components.Checkbox;
import ohos.agp.components.Text;
import ohos.app.Context;

import java.util.List;

/**
 * 设备数据提供者
 */
public class DeviceDataProvider extends ListComponentProvider<DeviceData> {
    private static final String TAG = "DeviceDataProvider";

    private OnItemCheckBoxCheckedListener onItemCheckBoxCheckedListener;

    /**
     * 实例化新的设备数据提供程序。
     * @param context 上下文
     * @param listBean 列表数据
     * @param resourceId 资源id
     */
    public DeviceDataProvider(Context context, List<DeviceData> listBean, int resourceId) {
        super(context, listBean, resourceId);
    }

    public void setOnItemCheckBoxCheckedListener(OnItemCheckBoxCheckedListener onItemCheckBoxCheckedListener) {
        if (onItemCheckBoxCheckedListener != null) {
            this.onItemCheckBoxCheckedListener = onItemCheckBoxCheckedListener;
        } else {
            LogUtil.warn(TAG, "setOnItemCheckBoxCheckedListener null");
        }
    }

    /**
     * 数据项绑定
     * @param componentViewHolder ViewHolder
     * @param deviceData 设备数据
     * @param position 索引
     */
    @Override
    public void onItemDataBind(ComponentViewHolder componentViewHolder, DeviceData deviceData, int position) {
        // 1 设置设备的名称
        Text deviceText = (Text) componentViewHolder.getChildComponent(ResourceTable.Id_item_image_title);
        if (deviceData.isLocal()) {
            deviceText.setText("本机");
        } else {
            deviceText.setText(deviceData.getDeviceName());
        }

        // id
        Text infoText = (Text) componentViewHolder.getChildComponent(ResourceTable.Id_item_image_info);
        infoText.setText(deviceData.getDeviceId());

        // 2 设置设备的图标 setDeviceImg(componentViewHolder, deviceData);
        Checkbox check = (Checkbox) componentViewHolder.getChildComponent(ResourceTable.Id_check);
        check.setChecked(deviceData.isChecked());
        check.setCheckedStateChangedListener((button, isChecked) -> {
            if (onItemCheckBoxCheckedListener != null) {
                onItemCheckBoxCheckedListener.onItemCbCheckedChangedListener(position, isChecked);
            }
        });
    }

    interface OnItemCheckBoxCheckedListener {
        void onItemCbCheckedChangedListener(int itemPosition, boolean isChecked);
    }
}
